package com.file.parser;

import com.file.bo.AppJszwfw;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 江苏不动产解析
 * @author anyspa
 */

@Slf4j
public class AppJszwfwHtmlParser {
    public ResponseData<String> parseAppJszwfwHtmlToJson(String daId, String filePath) {
        log.info("parseAppJszwfwHtmlToJson started, daId:{}", daId);
        String json = null;

        try {
            AppJszwfw appJszwfw = parseAppJszwfwHtml(filePath);
            json = JsonUtils.convertObjectToJson(appJszwfw);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAppJszwfwHtmlToJson failed", e);
            return new ResponseData<>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAppJszwfwHtmlToJson completed, daId:{}, json:{}", daId, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private AppJszwfw parseAppJszwfwHtml(String filePath) throws IOException {
        File input = new File(filePath);
        AppJszwfw appJszwfw = new AppJszwfw();

        Document doc = Jsoup.parse(input, "UTF-8");
        // 2022-06-07 09:38:08，根据崔文丽申请，经查询，结果如下：
        String resultTitle = getElementTextById(doc, "result-title");
        if (StringUtils.isNotBlank(resultTitle)) {
            Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}");
            Matcher matcher = pattern.matcher(resultTitle);
            if (matcher.find()) {
                appJszwfw.setQueryDate(matcher.group());
            }
            String name = resultTitle.substring(resultTitle.indexOf("根据") + 2, resultTitle.indexOf("申请，经查询"));
            appJszwfw.setName(name);
        } else {
            appJszwfw.setQueryDate(StringUtils.EMPTY);
            appJszwfw.setName(StringUtils.EMPTY);
        }

        AppJszwfw.NaturalStatus naturalStatus = new AppJszwfw.NaturalStatus();
        naturalStatus.setLocated(getElementTextById(doc, "zl"));
        naturalStatus.setHouseStructure(getElementTextById(doc, "fwjg"));
        naturalStatus.setHousePurposes(getElementTextById(doc, "fwyt"));
        naturalStatus.setConstructionArea(getElementTextById(doc, "jzmj"));
        naturalStatus.setInsideConstructionArea(getElementTextById(doc, "zyjzmj"));
        naturalStatus.setExclusiveLandArea(getElementTextById(doc, "dztdmj"));
        appJszwfw.setNaturalStatus(naturalStatus);

        AppJszwfw.OwnershipStatus ownershipStatus = new AppJszwfw.OwnershipStatus();
        ownershipStatus.setRealEstateUnitNumber(getElementTextById(doc, "bdcdyh"));
        ownershipStatus.setNatureOfHouse(getElementTextById(doc, "fwxz"));
        ownershipStatus.setTermOfLandUseRight(getElementTextById(doc, "tdsyqqx"));
        ownershipStatus.setNatureOfLandRights(getElementTextById(doc, "tdqlxz"));
        ownershipStatus.setCertificate(getElementTextById(doc, "bdcqzh"));
        ownershipStatus.setCheckInTime(getElementTextById(doc, "djsj"));
        ownershipStatus.setSharedWay(getElementTextById(doc, "gyqk"));
        ownershipStatus.setSharedPeople(getElementTextById(doc, "gyr"));
        appJszwfw.setOwnershipStatus(ownershipStatus);

        Elements trElements = doc.select("tbody > tr");
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < trElements.size(); i++) {
            Element element = trElements.get(i).selectFirst("td");
            if (Objects.nonNull(element) && element.hasAttr("id")) {
                if ("dy-title".equals(element.attr("id"))) {
                    // "抵押情况" 所在的 <tbody> <tr> 标签的起始index
                    map.put("dy-title", i);
                } else if ("xz-title".equals(element.attr("id"))) {
                    // "权利限制" 所在的 <tbody> 下 <tr> 标签的起始index
                    map.put("xz-title", i);
                }
            }
        }

        // 抵押情况 起始index
        Integer dyTitleStartIndex = null;
        // 权利限制 起始index
        Integer xzTitleStartIndex = null;

        if (map.containsKey("dy-title")) {
            dyTitleStartIndex = map.get("dy-title");
        }
        if (map.containsKey("xz-title")) {
            xzTitleStartIndex = map.get("xz-title");
        }

        // 抵押情况 和 权利限制 都不为空
        if (Objects.nonNull(dyTitleStartIndex) && Objects.nonNull(xzTitleStartIndex)) {
            List<AppJszwfw.MortgageStatus> mortgageStatusList = new ArrayList<>();
            for (int i = dyTitleStartIndex + 1; i < xzTitleStartIndex; i++) {
                Elements dyTitleElements = trElements.get(i).select("td");

                if (dyTitleElements.size() == 5) {
                    AppJszwfw.MortgageStatus mortgageStatus = new AppJszwfw.MortgageStatus();
                    mortgageStatus.setMortgagee(dyTitleElements.get(0).text());
                    mortgageStatus.setMortgageAmount(dyTitleElements.get(1).text());
                    mortgageStatus.setMortgagePeriod(dyTitleElements.get(2).text());
                    mortgageStatus.setRealEstateRegistrationCertificateNo(dyTitleElements.get(3).text());
                    mortgageStatus.setCheckInTime(dyTitleElements.get(4).text());
                    mortgageStatusList.add(mortgageStatus);
                }
            }
            appJszwfw.setMortgageStatuses(mortgageStatusList);

            List<AppJszwfw.RestrictionOfRights> restrictionOfRightsList = new ArrayList<>();
            for (int i = xzTitleStartIndex + 1; i < trElements.size(); i++) {
                Elements xzTitleElements = trElements.get(i).select("td");

                if (xzTitleElements.size() == 5) {
                    AppJszwfw.RestrictionOfRights restrictionOfRights = new AppJszwfw.RestrictionOfRights();
                    restrictionOfRights.setRestrictedPerson(xzTitleElements.get(0).text());
                    restrictionOfRights.setRestrictedCategory(xzTitleElements.get(1).text());
                    restrictionOfRights.setRestrictedDocumentNumber(xzTitleElements.get(2).text());
                    restrictionOfRights.setRestrictedPeriod(xzTitleElements.get(3).text());
                    restrictionOfRights.setCheckInTime(xzTitleElements.get(4).text());
                    restrictionOfRightsList.add(restrictionOfRights);
                }
            }
            appJszwfw.setRestrictionOfRights(restrictionOfRightsList);

        } else {
            log.info("parseAppJszwfwHtmlToJson getElementsById error, can not find id:[#dy-title] or [#xz-title] in html");
            List<AppJszwfw.MortgageStatus> mortgageStatusList = new ArrayList<>();
            AppJszwfw.MortgageStatus mortgageStatus = new AppJszwfw.MortgageStatus();
            mortgageStatus.setMortgagee(StringUtils.EMPTY);
            mortgageStatus.setMortgageAmount(StringUtils.EMPTY);
            mortgageStatus.setMortgagePeriod(StringUtils.EMPTY);
            mortgageStatus.setRealEstateRegistrationCertificateNo(StringUtils.EMPTY);
            mortgageStatus.setCheckInTime(StringUtils.EMPTY);
            mortgageStatusList.add(mortgageStatus);
            appJszwfw.setMortgageStatuses(mortgageStatusList);

            List<AppJszwfw.RestrictionOfRights> restrictionOfRightsList = new ArrayList<>();
            AppJszwfw.RestrictionOfRights restrictionOfRights = new AppJszwfw.RestrictionOfRights();
            restrictionOfRights.setRestrictedPerson(StringUtils.EMPTY);
            restrictionOfRights.setRestrictedCategory(StringUtils.EMPTY);
            restrictionOfRights.setRestrictedDocumentNumber(StringUtils.EMPTY);
            restrictionOfRights.setRestrictedPeriod(StringUtils.EMPTY);
            restrictionOfRights.setCheckInTime(StringUtils.EMPTY);
            restrictionOfRightsList.add(restrictionOfRights);
            appJszwfw.setRestrictionOfRights(restrictionOfRightsList);
        }

        return appJszwfw;
    }

    private String getElementTextById(Document doc, String id) {
        Element element = doc.getElementById(id);
        if (Objects.nonNull(element)) {
            return element.text();
        } else {
            log.info("parseAppJszwfwHtmlToJson getElementTextById error, can not find id:{} in html", id);
            return StringUtils.EMPTY;
        }
    }

    public static void main(String[] args) {
        String filePath = "D:\\data\\file\\appJszwfw\\bdc_zm.html";
        AppJszwfwHtmlParser appJszwfwHtmlParser = new AppJszwfwHtmlParser();
        String json = appJszwfwHtmlParser.parseAppJszwfwHtmlToJson("", filePath).getData();
        System.out.println(json);
    }
}
